package com.ruoyi.yey.parent;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.yey.bill.BillEntity;
import com.ruoyi.yey.bill.BillService;
import com.ruoyi.yey.parent.model.ParentAddModel;
import com.ruoyi.yey.parent.model.ParentEditModel;
import com.ruoyi.yey.parent.model.ParentSelectModel;
import com.ruoyi.yey.parent.model.ParentStuAddModel;
import com.ruoyi.yey.parent.student.ParentStudentEntity;
import com.ruoyi.yey.parent.student.ParentStudentService;

import com.ruoyi.yey.student.StudentEntity;
import com.ruoyi.yey.student.StudentService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;

@Service
public class ParentService extends ServiceImpl<ParentMapper,ParentEntity> {

    @Autowired
    private ParentStudentService parentStudentService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private BillService billService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 更新订单之中的积分到用户表里
     * @return
     */
    @Transactional
    public AjaxResult infoJiFen(){
        //获取订单里的用户信息
        List<BillEntity> billEntityList = billService.list(
                new QueryWrapper<BillEntity>()
                        .select("parent_id,sum(bill_price) as jifen")
                        .groupBy("parent_id")
        );
        System.out.println("===============查询的订单信息=============");
        billEntityList.forEach(e ->{System.out.println(e);});
        //获取家长列表
        List<ParentEntity> parentEntityList = list();
        parentEntityList.forEach(p ->{
            billEntityList.forEach(e ->{
                //对照一下赋值
                if (p.getId().equals(e.getParentId())){
                    p.setJifen(e.getJifen());
                    updateById(p);  //更新数据库的积分
                }
            });
        });
        return AjaxResult.success("更新订单积分成功");
    }

    /**
     * 获取积分列表
     * @return
     */
    public AjaxResult jiFenList(){
        //获取家长列表
        List<ParentEntity> list = list();
        //存入redis，用zset
        String key = "rank:employee";
        list.forEach(e ->{
            redisTemplate.opsForZSet().incrementScore(key, e.getParentVxid(), e.getJifen());
        });
        //获取
// 查询排行榜全部数据按照分数从大到小排序
        Set<ZSetOperations.TypedTuple<Object>> set1 = redisTemplate.opsForZSet().reverseRangeWithScores(key, 0L, -1L);
        System.out.println("查询排行榜全部数据按照分数从大到小排序：");
        LinkedHashMap<Object,Double> map = new LinkedHashMap<>();
        set1.forEach(tuple -> {
            System.out.println(tuple.getValue()+":"+tuple.getScore());
            map.put(tuple.getValue(),tuple.getScore());
        });
        return AjaxResult.success(map);
    }

    /**
     * 分页+模糊查询
     * @param page
     * @param searchModel
     * @return
     */
    public Page<Map> findAllByPage(Page page, ParentEntity searchModel) {
        return baseMapper.findBySearchVo(page,searchModel);
    }

    /**
     * 新增操作
     * @param parent
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(ParentAddModel parent) {

      ParentEntity parentEntity = new ParentEntity();
      parentEntity.setParentEntity(parent);
      //添加parent表
      baseMapper.insert(parentEntity);
        if (parent.getStudentIdList()!=null) {
            saveParentStudent(parentEntity.getId(), parent.getStudentIdList());
        }
    }

    /**
     * 用于添加parent_student表
     */
    private void saveParentStudent(int parentId, List<Integer> studentIdList){

        parentStudentService.delByParentId(parentId);
        if (!Objects.isNull(studentIdList) && !studentIdList.isEmpty()) {
            List<ParentStudentEntity> studentList = CollectionUtil.newArrayList();
            for (int studentId : studentIdList) {
                //创建parent_student对象 对应表parent_student字段
                ParentStudentEntity parentStudentEntity = new ParentStudentEntity();
                parentStudentEntity.setParentId(parentId);
                parentStudentEntity.setStudentId(studentId);
                studentList.add(parentStudentEntity);
            }
            parentStudentService.saveBatch(studentList);
        }
    }


    /**
     * 根据id查询家长以及对应的学生信息
     * @param id
     * @return
     */

    public ParentSelectModel findStuById(int id){
        return  baseMapper.findStuById(id);
    }
    public ParentSelectModel findById(int id){
        return  baseMapper.findById(id);
    }


    /**
     * 修改家长信息
     * @param parent
     */
    @Transactional(rollbackFor = Exception.class)
    public void edit(ParentEditModel parent){
        ParentEntity parentEntity = baseMapper.selectById(parent.getId());
        parentEntity.setParentEntity(parent);
        baseMapper.updateById(parentEntity);
        saveParentStudent(parentEntity.getId(),parent.getStudentIdList());

    }

    /**
     * 根据id
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public void delByIds(int id) {
        parentStudentService.delByParentId(id);
        baseMapper.deleteById(id);
    }

    /**
     * 家长关联学生
     * @param ps
     */
    @Transactional(rollbackFor = Exception.class)
    public void parentStuAdd(ParentStuAddModel ps){
        int parentId = ps.getParentId();
        int studentId = ps.getStudentId();
        if(ObjectUtils.isEmpty(parentStudentService.findOne(parentId,studentId))){
            ParentStudentEntity parentStudentEntity = new ParentStudentEntity();
            parentStudentEntity.setParentId(parentId);
            parentStudentEntity.setStudentId(studentId);
            parentStudentService.save(parentStudentEntity);
        }


        //编辑学生信息
        studentService.update(new UpdateWrapper<StudentEntity>()
                .set("student_sex",ps.getStudentSex())
                .set("student_birthday",ps.getStudentBirthday())
                .eq("id",studentId));
    }

    /**
     * 家长取消关联的学生
     * @param ps
     */
    @Transactional(rollbackFor = Exception.class)
    public void parentStuDel(ParentStudentEntity ps){
        parentStudentService.remove(
                new QueryWrapper<ParentStudentEntity>()
                        .eq("student_id",ps.getStudentId())
                        .eq("parent_id",ps.getParentId()));
    }

    @Transactional(rollbackFor = Exception.class)
    public int parentStuFind(ParentStudentEntity ps){
        if(ObjectUtil.isNotEmpty(parentStudentService.getOne(
                new QueryWrapper<ParentStudentEntity>()
                        .eq("student_id",ps.getStudentId())
                        .eq("parent_id",ps.getParentId())))){
            return 1;
        }else {
            return 0;
        }

    }

}
